package com.lxk.seckilldemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxk.seckilldemo.config.RedisConfig;
import com.lxk.seckilldemo.exception.GlobalException;
import com.lxk.seckilldemo.mapper.UserMapper;
import com.lxk.seckilldemo.pojo.User;
import com.lxk.seckilldemo.service.IUserService;
import com.lxk.seckilldemo.utils.CookieUtil;
import com.lxk.seckilldemo.utils.MD5Util;
import com.lxk.seckilldemo.utils.UUIDUtil;
import com.lxk.seckilldemo.utils.ValidatorUtil;
import com.lxk.seckilldemo.vo.LoginVo;
import com.lxk.seckilldemo.vo.RespBean;
import com.lxk.seckilldemo.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.validation.Validator;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-07-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public RespBean doLogin(HttpServletRequest request, HttpServletResponse response, LoginVo loginvo) {
        String mobile=loginvo.getMobile();
        String password=loginvo.getPassword();
//        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        if(!ValidatorUtil.isMobile(mobile))return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        User user=userMapper.selectById(mobile);
        if(user==null) throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        if(!user.getPassword().equals(MD5Util.FromPassToDBPass(password,user.getSalt()))){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        String ticket= UUIDUtil.uuid();
        //request.getSession().setAttribute(ticket,user);
        redisTemplate.opsForValue().set("user"+ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        return RespBean.success(ticket);
    }

    @Override
    public User getUserByCookies(HttpServletRequest request, HttpServletResponse response, String ticket) {
        if(ticket==null)return null;
        User user=(User)redisTemplate.opsForValue().get("user"+ticket);
        if(user!=null){
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }
        return user;
    }

}
